package com.seqb.utils;

import com.seqb.common.ColumnDO;
import com.seqb.common.Constant;
import com.seqb.common.TableDO;
import com.seqb.exception.BdException;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author lilinshen
 * @title 代码生成器 工具类
 * @description 请填写相关描述
 * @date 2019/11/12
 */
public class GenUtils {

    private static final String UNDERLINE = "_";
    private static final String DOAMIN_JAVA_VM = "domain.java.vm";
    private static final String DAO_JAVA_VM = "Dao.java.vm";
    private static final String SERVICE_JAVA_VM = "Service.java.vm";
    private static final String SERVICEIMPL_JAVA_VM = "ServiceImpl.java.vm";
    private static final String CONTROLLER_JAVA_VM = "Controller.java.vm";
    private static final String MAPPER_XML_VM = "Mapper.xml.vm";
    private static final String LIST_HTML_VM = "list.html.vm";
    private static final String ADD_HTML_VM = "add.html.vm";
    private static final String EDIT_HTML_VM = "edit.html.vm";
    private static final String LIST_JS_VM = "list.js.vm";

    /**
     * 模板文件列表
     */
    public static List<String> getTemplates() {
        List<String> templates = new ArrayList<String>();
        templates.add("templates/common/generator/domain.java.vm");
        templates.add("templates/common/generator/Dao.java.vm");
        templates.add("templates/common/generator/Mapper.xml.vm");
        templates.add("templates/common/generator/Service.java.vm");
        templates.add("templates/common/generator/ServiceImpl.java.vm");
        templates.add("templates/common/generator/Controller.java.vm");
        templates.add("templates/common/generator/list.html.vm");
        templates.add("templates/common/generator/add.html.vm");
        templates.add("templates/common/generator/edit.html.vm");
        templates.add("templates/common/generator/list.js.vm");
        return templates;
    }

    /**
     * 生成代码
     */
    public static void generatorCode(Map<String, String> table, List<Map<String, String>> columns, ZipOutputStream zip) {
        //配置信息
        Configuration config = getConfig();
        //表信息
        TableDO tableDO = new TableDO();
        tableDO.setTableName(table.get("TABLENAME"));
        tableDO.setComments(table.get("TABLECOMMENT"));
        //表名转换成Java类名
        String className = tableToJava(tableDO.getTableName(), config.getString("tablePrefix"), config.getString("autoRemovePre"));
        tableDO.setClassName(className);
        tableDO.setClassname(StringUtils.uncapitalize(className));

        //列信息
        List<ColumnDO> columsList = new ArrayList<>();
        for (Map<String, String> column : columns) {
            ColumnDO columnDO = new ColumnDO();
            columnDO.setColumnName(column.get("COLUMNNAME"));
            columnDO.setDataType(column.get("DATATYPE"));
            columnDO.setDataPrecision(column.get("DATAPRECISION"));
            columnDO.setDataScale(column.get("DATASCALE"));
            columnDO.setComments(column.get("COLUMNCOMMENT"));
            columnDO.setIsNullable(column.get("ISNULLABLE"));
            //列名转换成Java属性名
            String attrName = columnToJava(columnDO.getColumnName());
            columnDO.setAttrName(attrName);
            columnDO.setAttrname(StringUtils.uncapitalize(attrName));
            //列的数据类型，转换成Java类型
            String attrType = null;
            //如果数字类型字段含小数点，则转换成Double类型
            if ("NUMBER".equals(columnDO.getDataType().toUpperCase()) && StringUtils.isNotEmpty(columnDO.getDataScale())
                    && StringUtils.isNumeric(columnDO.getDataScale()) && Integer.parseInt(columnDO.getDataScale()) > 0) {
                attrType = "Double";
            } else {
                attrType = config.getString(columnDO.getDataType(), "unknowType");
            }
            columnDO.setAttrType(attrType);
            //是否主键
            if ("P".equalsIgnoreCase(column.get("CONSTRAINT_TYPE")) && tableDO.getPk() == null) {
                tableDO.setPk(columnDO);
            }
            columsList.add(columnDO);
        }
        tableDO.setColumns(columsList);
        //没主键，则第一个字段为主键
        if (tableDO.getPk() == null) {
            tableDO.setPk(tableDO.getColumns().get(0));
        }
        //设置velocity资源加载器
        Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(prop);

        //封装模板数据
        Map<String, Object> map = new HashMap<>(16);
        map.put("tableName", tableDO.getTableName());
        map.put("comments", tableDO.getComments());
        map.put("pk", tableDO.getPk());
        map.put("className", tableDO.getClassName());
        map.put("classname", tableDO.getClassname());
        //模块名
        String moduleName = tableDO.getTableName().substring(tableDO.getTableName().indexOf("_") + 1);
        String sequence = new StringBuffer("SEQ_").append(moduleName.toUpperCase()).toString();
        if (moduleName.contains(UNDERLINE)) {
            moduleName = moduleName.substring(0, moduleName.indexOf("_")).toLowerCase();
        }
        map.put("moduleName", moduleName);
        map.put("sequence", sequence);
        map.put("pathName", config.getString("package").substring(config.getString("package").lastIndexOf(".") + 1));
        map.put("columns", tableDO.getColumns());
        map.put("package", config.getString("package"));
        map.put("author", config.getString("author"));
        map.put("email", config.getString("email"));
        map.put("datetime", DateUtils.format(new Date(), DateUtils.DATE_PATTERN));
        VelocityContext context = new VelocityContext(map);

        //获取模板列表
        List<String> templates = getTemplates();
        for (String template : templates) {
            //渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, "UTF-8");
            tpl.merge(context, sw);
            try {
                //添加到zip
                zip.putNextEntry(new ZipEntry(getFileName(template, tableDO.getClassname(), tableDO.getClassName(), config.getString("package"), config.getString("package").substring(config.getString("package").lastIndexOf(".") + 1), moduleName)));
                IOUtils.write(sw.toString(), zip, "UTF-8");
                IOUtils.closeQuietly(sw);
                zip.closeEntry();
            } catch (IOException e) {
                throw new BdException("渲染模板失败，表名：" + tableDO.getTableName(), e);
            }
        }
    }

    /**
     * 列名转换成Java属性名
     */
    public static String columnToJava(String columnName) {
        return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_", "");
    }

    /**
     * 表名转换成Java类名
     */
    public static String tableToJava(String tableName, String tablePrefix, String autoRemovePre) {
        if (Constant.AUTO_REOMVE_PRE.equals(autoRemovePre)) {
            if (StringUtils.isNotBlank(tablePrefix) && tableName.startsWith(tablePrefix)) {
                tableName = tableName.replaceFirst(tablePrefix, "");
            } else {
                tableName = tableName.substring(tableName.indexOf("_") + 1);
            }
        }
        if (StringUtils.isNotBlank(tablePrefix) && tableName.startsWith(tablePrefix)) {
            tableName = tableName.replaceFirst(tablePrefix, "");
        }
        return columnToJava(tableName);
    }

    /**
     * 获取配置信息
     */
    public static Configuration getConfig() {
        try {
            return new PropertiesConfiguration("generator.properties");
        } catch (ConfigurationException e) {
            throw new BdException("获取配置文件失败，", e);
        }
    }

    /**
     * 获取文件名
     */
    public static String getFileName(String template, String classname, String className, String packageFullName, String packageName, String moduleName) {
        String packagePath = "main" + File.separator + "java" + File.separator;
        if (StringUtils.isNotBlank(packageName)) {
            packagePath += packageFullName.replace(".", File.separator) + File.separator;
        }
        if (StringUtils.isNotBlank(moduleName)) {
            packagePath += moduleName.replace(".", File.separator) + File.separator;
        }
        if (template.contains(DOAMIN_JAVA_VM)) {
            return packagePath + "domain" + File.separator + className + "DO.java";
        }
        if (template.contains(DAO_JAVA_VM)) {
            return packagePath + "dao" + File.separator + className + "Dao.java";
        }
        if (template.contains(SERVICE_JAVA_VM)) {
            return packagePath + "service" + File.separator + className + "Service.java";
        }
        if (template.contains(SERVICEIMPL_JAVA_VM)) {
            return packagePath + "service" + File.separator + "impl" + File.separator + className + "ServiceImpl.java";
        }
        if (template.contains(CONTROLLER_JAVA_VM)) {
            return packagePath + "controller" + File.separator + className + "Controller.java";
        }
        if (template.contains(MAPPER_XML_VM)) {
            return "main" + File.separator + "resources" + File.separator + "mybatis" + File.separator
                    + packageName + File.separator + moduleName + File.separator + className + "Mapper.xml";
        }
        if (template.contains(LIST_HTML_VM)) {
            return "main" + File.separator + "resources" + File.separator + "templates" + File.separator
                    + packageName + File.separator + moduleName + File.separator + classname + ".list.html";
        }
        if (template.contains(ADD_HTML_VM)) {
            return "main" + File.separator + "resources" + File.separator + "templates" + File.separator
                    + packageName + File.separator + moduleName + File.separator + classname + ".add.html";
        }
        if (template.contains(EDIT_HTML_VM)) {
            return "main" + File.separator + "resources" + File.separator + "templates" + File.separator
                    + packageName + File.separator + moduleName + File.separator + classname + ".edit.html";
        }
        if (template.contains(LIST_JS_VM)) {
            return "main" + File.separator + "resources" + File.separator + "static" + File.separator + "custom" + File.separator + "appjs" + File.separator
                    + packageName + File.separator + moduleName + File.separator + classname + ".list.js";
        }
        return null;
    }

    /**
     * 驼峰转换为下划线
     */
    public static String humpToUnderline(String camelCaseName) {
        StringBuilder result = new StringBuilder();
        if (camelCaseName != null && camelCaseName.length() > 0) {
            result.append(camelCaseName.substring(0, 1).toLowerCase());
            for (int i = 1; i < camelCaseName.length(); i++) {
                char ch = camelCaseName.charAt(i);
                if (Character.isUpperCase(ch)) {
                    result.append("_");
                    result.append(Character.toLowerCase(ch));
                } else {
                    result.append(ch);
                }
            }
        }
        return result.toString();
    }

    /**
     * 下划线转换为驼峰
     */
    public static String underlineToHump(String underscoreName) {
        StringBuilder result = new StringBuilder();
        if (underscoreName != null && underscoreName.length() > 0) {
            boolean flag = false;
            for (int i = 0; i < underscoreName.length(); i++) {
                char ch = underscoreName.charAt(i);
                if ("_".charAt(0) == ch) {
                    flag = true;
                } else {
                    if (flag) {
                        result.append(Character.toUpperCase(ch));
                        flag = false;
                    } else {
                        result.append(ch);
                    }
                }
            }
        }
        return result.toString();
    }

}
